package name.fowler.refactoring.simplestore.persistence;

import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;

import name.fowler.refactoring.simplestore.domain.Customer;

public class CustomerRepository {
	
	@PersistenceUnit
	private EntityManagerFactory entityManagerFactory;
	
	public CustomerRepository() {};
	
	// This constructor is for testing only
	public CustomerRepository(EntityManagerFactory entityManagerFactory) {
		this.entityManagerFactory = entityManagerFactory;
	}
	
	public void addCustomer(Customer c) {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		entityManager.getTransaction().begin();
        entityManager.persist(c);
        entityManager.getTransaction().commit();
	}
	
	public void removeCustomer(Customer c) {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		entityManager.getTransaction().begin();
        entityManager.remove(c);
        entityManager.getTransaction().commit();
	}
	
	public void updateCustomer(Customer c) {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		entityManager.getTransaction().begin();
        entityManager.merge(c);
        entityManager.getTransaction().commit();
	}
	
	public List<Customer> queryAll() {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		List<Customer> customers = entityManager
				.createNamedQuery("Customer.findAll", Customer.class)
				.getResultList();
		entityManager.close();
		return customers;
	}
	
	public List<Customer> getByName(String name) {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		List<Customer> customers = entityManager
				.createNamedQuery("Customer.findByName", Customer.class)
				.setParameter("name", name)
				.getResultList();
		entityManager.close();
		return customers;
	}
}
